package com.lixinlei.mc.api.controller;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

@RestController
@RequestMapping("/linux/list")
public class LinuxPortListController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LinuxPortListController.class);

    @GetMapping("/port")
    public String listPort() {
        String res = null;
        CommPortIdentifier portId;
        Enumeration<?> portList;
        int bauds[] = { 9600, 19200, 57600, 115200 };    //检测端口所支持的波特率
        portList = CommPortIdentifier.getPortIdentifiers();
        LOGGER.info("短信设备端口连接测试...");
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                LOGGER.info("找到串口: " + portId.getName());
                for (int i = 0; i < bauds.length; i++) {
                    LOGGER.info("  Trying at " + bauds[i] + "...");
                    try {
                        SerialPort serialPort;
                        InputStream inStream;
                        OutputStream outStream;
                        int c;
                        String response;
                        serialPort = (SerialPort) portId.open(
                                "SMSLibCommTester", 1971);
                        serialPort
                                .setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
                        serialPort.setSerialPortParams(bauds[i],
                                SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                        inStream = serialPort.getInputStream();
                        outStream = serialPort.getOutputStream();
                        serialPort.enableReceiveTimeout(1000);
                        c = inStream.read();
                        while (c != -1)
                            c = inStream.read();
                        outStream.write('A');
                        outStream.write('T');
                        outStream.write('\r');
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                        }
                        response = "";
                        c = inStream.read();
                        while (c != -1) {
                            response += (char) c;
                            c = inStream.read();
                        }
                        if (response.indexOf("OK") >= 0) {
                            try {
                                LOGGER.info("  获取设备信息...");
                                outStream.write('A');
                                outStream.write('T');
                                outStream.write('+');
                                outStream.write('C');
                                outStream.write('G');
                                outStream.write('M');
                                outStream.write('M');
                                outStream.write('\r');
                                response = "";
                                c = inStream.read();
                                while (c != -1) {
                                    response += (char) c;
                                    c = inStream.read();
                                }
                                if (StringUtils.isBlank(res)) {
                                    res = portId.getName() + ":" + response.replaceAll("\\s+OK\\s+", "").replaceAll("\n", "").replaceAll("\r", "");
                                } else {
                                    res = res + ";" + portId.getName() + ":" + response.replaceAll("\\s+OK\\s+", "").replaceAll("\n", "").replaceAll("\r", "");
                                }
                                LOGGER.info("发现设备:"+ response.replaceAll("\\s+OK\\s+", "").replaceAll("\n", "").replaceAll("\r", ""));
                            } catch (Exception e) {
                                e.printStackTrace();
                                LOGGER.error("没有发现设备!" + e.getMessage());
                            }
                        } else{
                            LOGGER.info("没有发现设备!");
                        }
                        inStream.close();
                        outStream.close();
                        serialPort.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOGGER.error("没有发现设备!" + e.getMessage());
                    }
                }
            }
        }
        return res;
    }

}
